package team.you.change.service.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import team.you.change.dao.UserMapper;
import team.you.change.util.Result;
import team.you.change.pojo.User;
import team.you.change.service.UserService;
import team.you.change.util.SendEmail;
import team.you.change.util.UpUtils;
import team.you.change.util.YuoUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result getAllUsers(Integer page, Integer limit) {
        Result result = new Result();
        List<User> users = userMapper.selectAll(YuoUtil.getPage(page, limit), limit);
        Integer count = userMapper.getCount();
        return YuoUtil.setData(result, users, count);
    }

    @Override
    public Result del(String id) {
        Result result = new Result();
        User user = userMapper.selectByPrimaryKey(id);
        if (user != null) {
            try {
                return YuoUtil.crudMsg(userMapper.deleteByPrimaryKey(id), result);
            }catch (Exception e){
                return YuoUtil.setErrorMsg(e, result);
            }
        } else {
            result.setCode(500);
            result.setMsg("用户不存在");
        }
        return result;
    }

    @Override
    @Transactional //添加事务
    //事务 做事时，要么全部成功，要么全部失败 如果出现异常，必须全部回滚
    public Result delete(String[] ids) {
        Result result = new Result();
        try {
            for (int i = 0; i < ids.length; i++) {
                userMapper.deleteByPrimaryKey(ids[i]);
            }
            return result;
        } catch (Exception e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result update(String id, String value, String field) {
        Result result = new Result();
        try {
            return YuoUtil.crudMsg(userMapper.UpdateByKey(id, value, field), result);
        } catch (Exception e) {
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result selectByLike(String value, Integer type, Integer page, Integer limit) {
        Result result = new Result();
        List<User> users = userMapper.selectByLike(value, type, YuoUtil.getPage(page, limit), limit); //模糊查询时分页
        List<User> count = userMapper.selectByLike(value, type, null, null);
        return YuoUtil.setData(result, users, count.size());
    }

    @Override
    public Result getTutorOption() {
        Result result = new Result();
        List<User> users = userMapper.selectAllId();
        if(users.size() > 0){
            result.setData(users);
            return result;
        }else{
            return YuoUtil.setFlaseMsg(result);
        }
    }

    @Override
    public Result upImg(MultipartFile file, HttpServletRequest request) {
        Result result = new Result();
        try {
            String path = UpUtils.fileUp(file, request);
            if(path != null){
                String fileName = file.getOriginalFilename(); //文件名
                result.setMsg(fileName);
                List<String> list = new ArrayList<>();
                list.add(path);
                result.setData(list);
                return result;
            }else {
                return YuoUtil.setFlaseMsg(result);
            }
        } catch (Exception e) {
           return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result editInfo(String id,String username, String realName, String idNumber, String head, HttpServletRequest request) {
        Result result = new Result();
        try {
            Result result1 = YuoUtil.crudMsg(userMapper.editInfo(id, username, realName, idNumber, head), result);
            return updateSession(result1, result, request, id);
        }catch (Exception e){
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    @Override
    public Result emailCode(List<String> email, HttpServletRequest request) {
        int email_code = (int)((Math.random()*9+1)*100000);
        ExecutorService executorService = Executors.newSingleThreadExecutor(); //线程池
        //提交线程到线程池
        executorService.submit(() ->
                email.forEach((e) -> SendEmail.mail(e, "邮箱验证码", "你的邮箱验证码是：" + email_code + "。\n有效时间5分钟，请尽快填写。\n如非本人操作，请忽略此消息！")));
        request.getSession().setAttribute("emailCode", email_code);
        request.getSession().setMaxInactiveInterval(300);
        return new Result();
    }

    @Override
    public Result edit(String id, String value, Integer type, HttpServletRequest request) {
        Result result = new Result();
        try {
            Result result1 = YuoUtil.crudMsg(userMapper.edit(id, value, type), result);
            return updateSession(result1, result, request, id);
        }catch (Exception e){
            return YuoUtil.setErrorMsg(e, result);
        }
    }

    /**
     * 更新用户服务端session和浏览器session
     * @param result1 更新用户信息结果
     * @param result 返回
     * @param request request对象
     * @param id 修改用户id
     * @return 返回
     */
    private Result updateSession(Result result1, Result result, HttpServletRequest request, String id){
        if(result1.getCode() == 0){
            User user = userMapper.selectByPrimaryKey(id);
            if(user != null){  //更新用户信息
                request.getSession().setAttribute("user", user);
                List<User> list = new ArrayList<>();
                list.add(user);
                result.setData(list);
                return result;
            }else{
                return YuoUtil.setFlaseMsg(result);
            }
        }else {
            return YuoUtil.setFlaseMsg(result);
        }
    }
}
